package com.cet.qz.unit01.chapter1_3;

import java.util.Iterator;

/**
 * @program: algorithm
 * @description: 使用一个双向队列维护两个栈
 * @author: 陈恩涛
 * @create: 2021-04-27 14:40
 **/
public class TwoStack<Item> implements Iterable<Item> {

    private Deque<Item> deque;
    private int firstStackLength;
    private int secondStackLength;

    public TwoStack() {
        deque = new Deque<>();
        firstStackLength = 0;
        secondStackLength = 0;
    }

    public boolean isEmpty() {
        return firstStackLength == 0 && secondStackLength == 0;
    }

    public int getFirstStackLength() {
        return firstStackLength;
    }

    public int getSecondStackLength() {
        return secondStackLength;
    }

    public int size() {
        return firstStackLength + secondStackLength;
    }

    public void pushToFirstStack(Item item) {
        deque.pushLeft(item);
        firstStackLength++;
    }

    public Item firstStackPop() {
        if (getFirstStackLength() == 0) {
            throw new RuntimeException("第一个栈已经为空了！");
        }
        firstStackLength--;
        return deque.popLeft();
    }

    public void pushToSecondStack(Item item) {
        deque.pushRight(item);
        secondStackLength++;
    }

    public Item secondStackPop() {
        if (getSecondStackLength() == 0) {
            throw new RuntimeException("第二个栈已经为空了！");
        }
        secondStackLength--;
        return deque.popRight();
    }

    @Override
    public Iterator<Item> iterator() {
        return new TwoStackIterator();
    }

    class TwoStackIterator implements Iterator<Item> {

        private Iterator<Item> iterator;

        public TwoStackIterator() {
            Queue<Item> queue = new Queue<>();
            for (Item item : deque) {
                queue.enqueue(item);
            }
            iterator = queue.iterator();
        }

        @Override
        public boolean hasNext() {
            return iterator.hasNext();
        }

        @Override
        public Item next() {
            return iterator.next();
        }

        @Override
        public void remove() {

        }
    }

    public static void main(String[] args) {
        TwoStack<Integer> twoStack = new TwoStack<>();
        twoStack.pushToFirstStack(1);
        twoStack.pushToFirstStack(2);
        twoStack.pushToFirstStack(3);
        twoStack.pushToSecondStack(4);
        for (Integer i : twoStack) {
            System.out.print(i + " ");
        }
        System.out.println(twoStack.secondStackPop());
        twoStack.secondStackPop();
    }

}
